import React, { PureComponent } from "react";
import { FormattedMessage, formatMessage } from "umi-plugin-react/locale";
import { Spin, Tag, Menu, Icon, Avatar, Tooltip, message, Badge, Button,Modal, Tabs } from "antd";
import moment from "moment";
import groupBy from "lodash/groupBy";
import NoticeIcon from "../NoticeIcon";
import HeaderDropdown from "../HeaderDropdown";
import SelectLang from "../SelectLang";
import styles from "./index.less";
import userImg from "@/assets/icons/user.png";
import fontJs from "@/assets/js/font_1286992_1lj8yl8vk59.js";
import { menuInfo, menuList } from "@/services/nav";
import UserSession from "@/UserSession";
import { Link } from "umi";
import { isFreeLancerUser } from "@/utils/utils.js"

import kfImg from "@/assets/kf.png";
import MyAccount from "@/pages/Account/Settings/myAccount";

const IconFont = Icon.createFromIconfontCN({
	scriptUrl: fontJs,
});

export default class GlobalHeaderRight extends PureComponent {
	getNoticeData() {
		const { notices = [] } = this.props;
		if (notices.length === 0) {
			return {};
		};
		const newNotices = notices.map((notice) => {
			const newNotice = { ...notice };
			if (newNotice.datetime) {
				newNotice.datetime = moment(notice.datetime).fromNow();
			};
			if (newNotice.id) {
				newNotice.key = newNotice.id;
			};
			if (newNotice.extra && newNotice.status) {
				const color = { todo: "", processing: "blue", urgent: "red", doing: "gold" }[newNotice.status];
				newNotice.extra = <Tag color={color} style={{ marginRight: 0 }}>{newNotice.extra}</Tag>;
			};
			return newNotice;
		});
		return groupBy(newNotices, "type");
	}

	getUnreadData = (noticeData) => {
		const unreadMsg = {};
		Object.entries(noticeData).forEach(([key, value]) => {
			if (!unreadMsg[key]) {
				unreadMsg[key] = 0;
			};
			if (Array.isArray(value)) {
				unreadMsg[key] = value.filter((item) => !item.read).length;
			};
		});
		return unreadMsg;
	};

	changeReadState = (clickedItem) => {
		const { id } = clickedItem;
		const { dispatch } = this.props;
		dispatch({
			type: "global/changeNoticeReadState",
			payload: id,
		});
	};

  menuClick = values => {
    if(values.key == 'userinfo'){
      this.MyAccount.initModal()
      return false
    }
    this.props.onMenuClick(values)
  }

	render() {
		let { currentUser, fetchingNotices, onNoticeVisibleChange, onMenuClick, onNoticeClear, theme, } = this.props;
		let isFreeLancer = false;
		if (!currentUser.uid) {
			currentUser = JSON.parse(localStorage.getItem("currentUser"));
		}
		if (currentUser) {
			isFreeLancer = isFreeLancerUser(currentUser);
		}
		const menu = (
			<Menu className={styles.menu} selectedKeys={[]} onClick={this.menuClick}>
				{!isFreeLancer && currentUser && currentUser.menus ? (
					<Menu.Item key='userinfo'>
						<Icon type='setting' />
						<FormattedMessage id='menu.account.accountSettings' defaultMessage='account settings' />
					</Menu.Item>
				) : ''}
				{!isFreeLancer && currentUser && currentUser.menus ? (
					<Menu.Divider />
				) : ''}
				<Menu.Item key='logout'>
					<Icon type='logout' />
					<FormattedMessage id='menu.account.logout' defaultMessage='logout' />
				</Menu.Item>
			</Menu>
		);
		const noticeData = this.getNoticeData();
		let className = styles.right;
		if (theme === "dark") {
			className = `${styles.right}  ${styles.dark}`;
		};
		if (!currentUser) {
			currentUser = "";
		};
		const robotId = !currentUser ? "" : currentUser.robotId;
		const robotUrl = customBaseUrl + "/web?robotId=" + robotId;
		const userImg = currentUser && currentUser.picture ? currentUser.picture : "/robotConfigImg/user.png";


		return (
			<div className={className}>
				{/* {currentUser && currentUser.uid != 1 ? ( */}
				{/*   <span> */}
				{/*     <IconFont type="icon-robot1" style={{ background: 'deepskyblue', padding: 3, borderRadius: 10 }} /> */}
				{/*     <a href={robotUrl} target="_blank" className={styles.action}>我的机器人</a> */}
				{/*   </span> */}
				{/* ) : null} */}

				{UserSession.hasArtificialCenter() && (UserSession.hasIM() || UserSession.hasTicket()) ? (
					<span
						style={{
							cursor: "pointer",
							color: "#576675",
							userSelect: "none",
						}}
						onClick={() => {
							if (UserSession.canJumpToOtherMenu()) {
								window.open(window.kefuUrl);
							}
						}}
					>
						<img src={kfImg} alt='' style={{ width: 28,verticalAlign:"middle" }} />
						<span style={{ marginLeft: 10 }}>前往客服系统</span>
					</span>
				) : ''}

				{/* <a href='/notice' rel='noopener noreferrer' className={styles.action}>
					<Badge count={currentUser.unReadNoticeCount}>
						<Icon
							type='bell'
							className={styles.action}
							style={{ fontSize: 20, marginRight: -7 }}
						/>
					</Badge>
				</a> */}

				{/* <NoticeIcon className={styles.action} count="6"></NoticeIcon> */}
				{/* <span>
					<a href={"/help/mannual/#"} target='_blank' className={styles.action}>
						<Button style={{ background: "#FB9505", borderColor: "#FB9505", color: "#ffffff" }}>操作手册</Button>
					</a>
					<a href={"/help/#/"} target='_blank' className={styles.action}>
						<Button type={"primary"}>知识库运营方案</Button>
					</a>
				</span> */}

				<SelectLang className={styles.action} />

				<HeaderDropdown overlay={menu}>
					<span className={`${styles.action} ${styles.account}`}>
						<Avatar size='small' className={styles.avatar} src={userImg} alt='avatar' />
						<span className={styles.name}>{currentUser.nick}</span>
					</span>
				</HeaderDropdown>

        <MyAccount onRef={ref => this.MyAccount = ref} />
			</div>
		);
	}
}
